<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\App;
use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use app\common\model\Pro;
use app\common\model\ProPlace;
use app\common\model\CheckList;
use app\common\model\CheckListDetails;
use app\common\model\District;
use app\common\model\DistrictPro;
use think\facade\View;
use think\response\Json;

use app\common\tool\excel\Export;

class Company extends Base
{

    //主键
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\Company';

    //关联模型
    protected $hasOne = ['pro', 'proplace', 'district'];

    public function index()
    {
        return $this->setTable();
    }

    //自动构建table,按需修改
    public function setTable()
    {
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'field' => '', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'company_name', 'title' => '场所/单位名', 'format' => 'input', 'width' => 300])
            ->addRow(['field' => 'protitle', 'title' => '所属项目', 'templet' => '<div>{{d.pro.title}}</div>'])
            ->addRow(['field' => 'districttitle', 'title' => '所属区域', 'templet' => '<div>{{d.district.title}}</div>'])
            ->addRow(['field' => 'address', 'title' => '场所地址', 'format' => 'input', 'width' => 300])
            ->addRow(['field' => 'fzname', 'title' => '消防负责人', 'format' => 'input'])
            ->addRow(['field' => 'lxtel', 'title' => '联系电话',  'format' => 'input'])
            ->addRow(['field' => 'area', 'title' => '场所面积',  'format' => 'input', 'width' => 100])
            ->addRow(['field' => 'height', 'title' => '建筑高度',  'format' => 'input'])
            ->addRow(['field' => 'status', 'title' => '异常状态',  'format' => 'input', 'templet' => '#CompanyTpl'])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 200]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addRightButtons([
                'showmap' => [
                    'type' => 'edit',
                    'title' => '查看详情',
                    'width' => 1400,
                    'height' => 1200,
                    'class'  => 'layui-btn layui-btn-sm',
                    'url' => url('company/showmap', ['name' => request()->controller() . '_' . request()->action()])->build(),
                ],
                'delete' => [
                    'type' => 'delete',
                    'title' => '删除',
                    'width' => 1400,
                    'height' => 1200,
                    'class'  => 'layui-btn-danger layui-btn layui-btn-sm right_button',
                    'url' => url('company/companydel', ['name' => request()->controller() . '_' . request()->action()])->build(),
                ]
            ])
            //->addTopButtons(['deleteAll'])
            ->setSearch($this->setSearch(), false)
            ->addExtraHtml(['companystatus'])
            ->fetch('company/index');
    }
    //自动构建Search，按需修改
    public function setSearch()
    {
        $pro = Pro::proSelect();
        $district = District::districtSelect();
        return TableFront::getInstance()
            ->setSearch(['company_name', '场所/单位名', 'input', '', '', '', 'like'])
            ->setSearch(['pro_id', '所属项目', 'select', $pro])
            ->setSearch(['district_id', '场所区域', 'select', $district]);
    }
    public function showmap($id = '')
    {
        $info = $this->model::with(['pro', 'proplace'])->find($id);
        View::assign(['info' => $info]);
        return View::fetch();
    }

    //导入为excel文件
    public function importcompanyexcel(): Json
    {
        $param = $this->request->param();
        $data = htmlspecialchars_decode($param['persons']);
        $list = json_decode($data, true);
        foreach ($list as $k => $v) {
            $find = $this->model::where(['company_name' => $v['场所/单位名']])->find();
            $infos = DistrictPro::where(['id' => $v['所属社区'], 'is_del' => 0])->find();
            if(!empty($infos)){
                $companydata['company_name'] = $v['场所/单位名'];
                $companydata['place_id'] = $infos['id'];
                $companydata['pro_id'] = $infos['pro_id'];
                $companydata['district_id'] = $param['district_id'];
                if (!empty($v['消防负责人'])) {
                    $companydata['fzname'] = $v['消防负责人'];
                }
                if (!empty($v['联系电话'])) {
                    $companydata['lxtel'] = $v['联系电话'];
                }
                if (!empty($v['经营面积'])) {
                    $companydata['area'] = $v['经营面积'];
                }
                if (!empty($v['出租屋高度'])) {
                    $companydata['height'] = $v['出租屋高度'];
                }
                if (!empty($v['场所地址'])) {
                    $companydata['address'] = $v['场所地址'];
                }
                $company = $this->model::create($companydata);
                $checkfind = CheckList::where(['company_id' => $company->id])->find();
                if ($company) {
                    if (empty($checkfind)) {
                        $checkdata['company_id'] = $company->id;
                        $checkdata['pro_id'] = $companydata['pro_id'];
                        $checkdata['district_id'] = $companydata['district_id'];
                        $checkdata['one_status'] = 1;
                        CheckList::create($checkdata);
                    }
                }
            }
        }
        return json(['code' => 1, 'msg' => '导入成功！']);
    }
    /**
     * 导出数据
     */

    public function exportAddExcel()
    {
        $param = $this->request->param();
        $fileName = "场所信息-" . date('YmdHis') . '.xlsx';
        $headArr = ['场所/单位名', '所属项目', '场所地址', '消防负责人', '联系电话', '经营面积', '场所得分', '隐患条数'];
        $list = $this->model::where(['is_del' => 0])->select()->toArray();
        foreach ($list as $k => $v) {
            $pro = Pro::where(['id' => $v['pro_id']])->value('title');
            $v['proname'] = $pro;
            $v['score'] = CheckList::where(['company_id' => $v['id'], 'one_status' => 2])->value('one_score');
            $v['yhcount'] = CheckListDetails::where(['company_id' => $v['id'], 'types' => 1])->count();
            $list[$k] = $v;
        }
        //print('<pre>');print_r($list);die;
        $sort = array_column($list, 'score');
        array_multisort($sort, SORT_DESC, $list);

        foreach ($list as $k => $v) {
            $data[] = [$v['company_name'], $v['proname'], $v['address'], $v['fzname'], $v['lxtel'], $v['area'], $v['score'], $v['yhcount']];
        }
        //print('<pre>');print_r($data);die;
        Export::excelExport($headArr, $data, $fileName);
    }

    /**
     * 原点 2021年7月27日14:46:29 公共删除方法
     */
    public function companydel(): Json
    {
        try {
            $id = $this->request->post('id');

            $model = $this->model::where('id', $id)->find();
            $model->is_del = 1;
            $model->save();
            $list = $this->model::order('id asc')->select();
            foreach ($list as $k => $v) {
                CheckList::where(['company_id' => $v['id']])->update(['is_del' => $v['is_del']]);
                CheckListDetails::where(['company_id' => $v['id']])->update(['is_del' => $v['is_del']]);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 原点 2021年7月27日14:46:29 公共删除方法
     */
    public function companyAlldel(): Json
    {
        try {
            $id = $this->request->post('ids');
            $ids = explode(',', $id);
            foreach ($ids as $v) {
                $model = $this->model::where('id', $v)->find();
                $model->is_del = 1;
                $model->save();
            }
            $list = $this->model::where(['is_del' => 1])->order('id asc')->select();
            foreach ($list as $k => $v) {
                CheckList::where(['company_id' => $v['id']])->update(['is_del' => 1]);
                CheckListDetails::where(['company_id' => $v['id']])->update(['is_del' => 1]);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
}
